<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';

const departments = ref([]); // 初始化为空数组
const currentPage = ref(1);
const pageSize = 10;

// 获取部门数据的方法
const fetchDepartments = async () => {
  try {
    const res = await axios.get('http://127.0.0.1:8080/admin/department/getAll',
    {
      headers:{
        token: localStorage.getItem("token")
      }
    }
    );
    console.log(res);
    if (res.data && res.data.data) {
      departments.value = res.data.data.map(item => ({
        deptId: item.departmentId,
        deptName: item.departmentName
      }));
    }
  } catch (e) {
    console.log('获取部门数据失败');
  }
};

onMounted(() => {
  fetchDepartments();
});

const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize;
  return departments.value.slice(start, start + pageSize);
});

const handlePageChange = (page) => {
  currentPage.value = page;
};

const tableRowClassName = ({ rowIndex }) =>
  rowIndex % 2 === 0 ? 'bg-white' : 'bg-gray-50';

// 删除部门的方法
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除部门 "${row.deptName}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // 从数组中删除该部门
      const index = departments.value.findIndex(dept => dept.deptId === row.deptId);
      if (index > -1) {
        departments.value.splice(index, 1);
        ElMessage({
          type: 'success',
          message: `部门 "${row.deptName}" 已成功删除`,
        });
        // 如果当前页没有数据了，且不是第一页，则跳转到上一页
        if (paginatedData.value.length === 0 && currentPage.value > 1) {
          currentPage.value--;
        }
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      });
    });
};
</script>

<template>
  <div class="min-h-screen bg-gray-50 p-8">
    <div class="mx-auto max-w-7xl">
      <!-- 标题区域 -->
      <div class="mb-8 text-center">
        <h1 class="text-3xl font-bold text-gray-800">部门列表</h1>
      </div>

      <!-- 表格区域 -->
      <div class="overflow-hidden rounded-lg bg-white shadow">
        <div class="overflow-x-auto">
          <el-table
            :data="paginatedData"
            stripe
            class="w-full"
            header-cell-class-name="bg-gray-100 font-semibold text-gray-700"
            :row-class-name="tableRowClassName"
          >
            <el-table-column prop="deptId" label="部门编号" width="200" />
            <el-table-column prop="deptName" label="部门名称" />
            <el-table-column label="操作" width="120" align="center">
              <template #default="scope">
                <el-button
                  type="danger"
                  size="small"
                  @click="handleDelete(scope.row)"
                  class="bg-red-500 hover:bg-red-600 border-red-500 hover:border-red-600"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页区域 -->
        <div class="flex justify-end p-4">
          <el-pagination
            background
            layout="total, prev, pager, next"
            :total="departments.length"
            :page-size="pageSize"
            v-model:current-page="currentPage"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>


